package com.xmqian.app.common.config.user;

import android.content.Context;

import com.coszero.utilslibrary.utils.SharedPreUtils;
import com.coszero.utilslibrary.utils.StringUtils;
import com.xmqian.app.project.MyApplication;
import com.xmqian.app.project.ui.user.model.LoginModel;


/**
 * Desc：用户信息管理类，用作登录
 * <p>
 * Author： xmqian
 * Email:xmqian93@163.com
 * Date: 2019/6/4 12:59
 */
public class UserManager {
    private static UserManager INSTANCE = null;
    private Context mContext;
    private boolean isLogin;//登录状态

    private UserManager(Context context) {
        mContext = context;
    }

    public static UserManager getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new UserManager(MyApplication.getAppContext());
        }
        return INSTANCE;
    }

    /**
     * 初始化登录状态
     */
    public void initLoginData() {
        LoginModel infoBean = getLoginData();
        if (null != infoBean && !StringUtils.isEmpty(infoBean.getToken())) {
            isLogin = true;
        } else {
            isLogin = false;
            clearLoginData();
        }
    }

    public boolean isLogin() {
        return isLogin;
    }

    /**
     * 保存登录信息到本地
     *
     * @param infoBean
     */
    public void saveLoginData(LoginModel infoBean) {
        SharedPreUtils.saveStringData(mContext, LoginConstance.USER_NICKNAME, infoBean.getUserName());
        SharedPreUtils.saveStringData(mContext, LoginConstance.USER_HEAD_IMAGE, infoBean.getHeadImage());
        SharedPreUtils.saveStringData(mContext, LoginConstance.USER_TOKEN, infoBean.getToken());
        isLogin = true;
    }

    public LoginModel getLoginData() {
        LoginModel loginModel = new LoginModel();
        loginModel.setUserName(SharedPreUtils.getStringData(mContext, LoginConstance.USER_NICKNAME, ""));
        loginModel.setHeadImage(SharedPreUtils.getStringData(mContext, LoginConstance.USER_HEAD_IMAGE, ""));
        loginModel.setToken(SharedPreUtils.getStringData(mContext, LoginConstance.USER_TOKEN, ""));
        return loginModel;
    }

    /**
     * 清除本地的用户登录信息
     */
    public void clearLoginData() {
        SharedPreUtils.clear(mContext);
    }

    /**
     * 用户需要存储的信息目录
     */
    private static class LoginConstance {
        public static final String USER_ACCOUNT = "USER_ACCOUNT";//用户账户
        public static final String USER_PASSWORD = "USER_PASSWORD";//用户密码，可不存，建议加密存储
        public static final String USER_NICKNAME = "USER_NICKNAME";//用户昵称,姓名
        public static final String USER_TOKEN = "USER_TOKEN";//用户唯一标识，用于请求
        public static final String USER_HEAD_IMAGE = "USER_HEAD_IMAGE";//用户头像
        public static final String USER_ROLES = "USER_ROLES";//用户角色，多角色登录需要
    }
}
